package com.ndood.core.social;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.social.config.annotation.SocialConfigurerAdapter;
import org.springframework.social.connect.ConnectionFactoryLocator;
import org.springframework.social.connect.ConnectionRepository;
import org.springframework.social.connect.web.ConnectController;
import org.springframework.social.security.SpringSocialConfigurer;
import org.springframework.web.servlet.View;

import com.ndood.core.properties.SecurityProperties;
import com.ndood.core.social.view.ConnectView;

/**
 * 添加Social配置类
 */
@Configuration
public class SocialBeanConfig extends SocialConfigurerAdapter{
	
	@Autowired
	private SecurityProperties securityProperties;
	
	@Autowired(required = false)
	private SocialAuthenticationFilterPostProcessor socialAuthenticationFilterPostProcessor;
	
	/**
	 * 声明SocialSecurityConfigurer Bean 
	 * 使用自己的filterProcessesUrl配置
	 * 如果自己实现了SpringSocialConfig，则不用这边的配置
	 */
	@Bean
	public SpringSocialConfigurer springSocialSecurityConfig(){
		String filterProcessesUrl = securityProperties.getSocial().getFilterProcessesUrl();
		SpringSocialConfig configurer = new SpringSocialConfig(filterProcessesUrl);

		// 社交首次登录，注册跳转到自定义signUpPage
		configurer.signupUrl(securityProperties.getBrowser().getSignUpPage());
		
		// 授权码模式-app和浏览器获取token后做出不同反应
		configurer.setSocialAuthenticationFilterPostProcessor(socialAuthenticationFilterPostProcessor);
		
		return configurer;
	}
	
	/**
	 * 微信绑定结果跳转
	 * weixinConnected绑定，weixinConnect解绑
	 * @return
	 */
	@Bean({"connect/weixinConnect", "connect/weixinConnected"})
	@ConditionalOnMissingBean(name = "weixinConnectedView")
	public View weixinConnectedView() {
		return new ConnectView();
	}
	
	/**
	 * QQ绑定结果跳转
	 * weixinConnected绑定，weixinConnect解绑
	 * @return
	 */
	@Bean({"connect/qqConnect", "connect/qqConnected"})
	@ConditionalOnMissingBean(name = "qqConnectedView")
	public View qqConnectedView() {
		return new ConnectView();
	}
	
	/**
	 * springboot升級2.0不支持ConnectedControllerbug
	 * https://github.com/psyfabriq/cloud-project
	 */
	@Bean
    public ConnectController connectController(ConnectionFactoryLocator connectionFactoryLocator, ConnectionRepository connectionRepository) {
        return new ConnectController(connectionFactoryLocator, connectionRepository);
    }
}